//
//  ViewController.m
//  317-网络请求
//
//  Created by user on 16/3/17.
//  Copyright © 2016年 M&M. All rights reserved.
/*
 e.g TestController 和 TestModel 为测试数据，开发时用自己提供的数据
 */
#import "XBActivityTableViewController.h"
#import "XBNewViewController.h"
#import "FindKnowlegeViewController.h"
#import "JingxuanViewController.h"

#import "Header.h"
#import "MainViewController.h"
#import "FlowLayout.h"
#import "XBCommunityScrollView.h"
#import "XBCommunityCell.h"
#import "XBCommunityLabel.h"

#import "XBPhotoPickerController.h"

@interface MainViewController () <UICollectionViewDataSource,UICollectionViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
/**value!*/
@property (nonatomic,assign) CGFloat value;

/** 频道标题数组(数据模型) */
@property (nonatomic,strong) NSArray *channelTitles;

/** 频道ScrollView */
@property (nonatomic,weak) XBCommunityScrollView *channelView;

/** 要展示内容的视图，根据实际需求可更改其定义 */
@property (nonatomic,weak) UICollectionView *collectionView;

/** FlowLayout */
@property (nonatomic,weak) UICollectionViewFlowLayout *flowLayout;

/** 颜色值 */
@property (nonatomic,assign) CGFloat colorValue;

/** 当前下标 */
@property (nonatomic,assign) NSInteger currentIndex;

/** 选中的标题 */
@property (nonatomic,weak) XBCommunityLabel *selectedLabel;

/** 相机点击item */
@property (nonatomic,strong) UIImageView *photoImageView;

/**搜索文本框*/
@property (weak, nonatomic) IBOutlet UITextField *searchField;

@end

@implementation MainViewController

#pragma mark - ======== ViewDidLoad ========
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(channelTitleDidSelected:) name:ChannelTitleCurrenIndexChanged object:nil];
    
    self.searchField.frame = CGRectMake(10, 0, 300, 32);
    [self.searchField addTarget:self action:@selector(touchSearch) forControlEvents:UIControlEventTouchDown];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupChannelView];      // 加载频道View
    [self setupCollectionView];   // 加载内容CollectionView
}
- (void)touchSearch
{
    UITableViewController *searchNav= [[UIStoryboard storyboardWithName:@"Search" bundle:nil] instantiateInitialViewController];
    //    [self.navigationController pushViewController:searchNav animated:NO];
    [self presentViewController:searchNav animated:NO completion:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 显示相机图片
    self.photoImageView.hidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 隐藏相机图片
    self.photoImageView.hidden = YES;
}

#pragma mark - ======== 相机item懒加载 ========
- (UIImageView *)photoImageView
{
    if (!_photoImageView) {

        UIImage *image = [UIImage imageNamed:@"tab_post_selected_nor"];
        _photoImageView = [[UIImageView alloc] initWithImage:image];
        // 点击事件
        _photoImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidClick)];
        [_photoImageView addGestureRecognizer:tap];
        // tabBar 添加一个按钮
        [self.tabBarController.tabBar addSubview:_photoImageView];
        /**********ss*/
        // 拿到图片的frame
        CGRect imageViewFrame = _photoImageView.frame;
        // 重新定位
        CGFloat imgViewX = [UIScreen mainScreen].bounds.size.width /5 * 2;
        imageViewFrame.origin.x = imgViewX;
        _photoImageView.frame = imageViewFrame;
    }
    return _photoImageView;
}
- (IBAction)cameraClick:(id)sender {
    [self imageViewDidClick];
}
// 相机item点击事件
- (void)imageViewDidClick
{
    // 获取手机的图片
    // UIImagePickerController
    XBPhotoPickerController *vc = [XBPhotoPickerController sharedPhotopicker];
    
    // modal
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - ======== 数据源 ========
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.channelTitles.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    __kindof UIViewController *vc = self.viewControllers[indexPath.row];
    
    // 创建cell
    XBCommunityCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID forIndexPath:indexPath];
    
    // 赋值控制器
    cell.viewController = vc;
    
    return cell;
}
- (NSArray<UIViewController *> *)viewControllers
{
    if (!_viewControllers) {
        // 赋值自定义的控制器
        JingxuanViewController *vc1 = [[JingxuanViewController alloc] init];
        XBNewViewController *vc2 = [[XBNewViewController alloc] init];
        FindKnowlegeViewController *vc = [[FindKnowlegeViewController alloc] init];
        XBActivityTableViewController *vc3 = [[XBActivityTableViewController alloc] init];
        _viewControllers = @[vc1,vc2,vc,vc3];
    }
    return _viewControllers;
}
#pragma mark - ======== 代理 ========
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 让非选中的标题大小恢复默认
//    for (ChannelLabel *label in self.channelView.subviews) {
//        
//        if (label.class != [UIView class] && label.scaleValue < 0.99) {
//            
//            label.scaleValue = 0;
//        }
//    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 偏移量
    CGFloat offsetX = scrollView.contentOffset.x;

    // 页面
    NSInteger nexIndex = (offsetX + ScreenW *0.5)/ ScreenW;
    
    // 脚线frame
    CGRect rect = self.channelView.footLine.frame;
    // 赋值脚线位置
    rect.origin.x = self.value + nexIndex * (rect.size.width+margin);
    // 动画移动
    [UIView animateWithDuration:0.26 animations:^{
        self.channelView.footLine.frame = rect;
    }];
    
    // 拿到当前
    XBCommunityLabel *label1 = self.channelView.subviews[nexIndex];
    // 改变颜色
    label1.textColor = [UIColor orangeColor];
    
    // 根据这个值的 正 或 负 来设置 preIndex
    CGFloat isValue = (nexIndex * ScreenW) / offsetX;
    
    // 需要拿到下一个的索引
    // 往右超过一半，就nexIndex+1
    // 往左超过一半，就nexIndex-1
    NSInteger preIndex =  isValue > 1.0 ? nexIndex - 1 : nexIndex + 1;
    
    // 防止越界
    if (preIndex == self.channelView.subviews.count-1) return;
    
    XBCommunityLabel *label2 = self.channelView.subviews[preIndex];
    // 改变颜色
    label2.textColor = [UIColor blackColor];
}

#pragma mark - ======== 通知 ========
- (void)channelTitleDidSelected:(NSNotification *)info
{
    // 拿到频道view传递过来的index
    NSNumber *index = info.userInfo[@"index"];
    // 重新赋值currentIndex
    self.currentIndex = index.integerValue;
    
    // 滚动cell到指定的位置
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index.integerValue inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

#pragma mark - ======== 加载子控件 ========
- (void)setupChannelView
{
    CGFloat tabbarH = self.tabBarController.tabBar.frame.size.height;
    // 添加频道View
    // 获得frame
    CGRect frame = CGRectMake(0, StatusBarMaxY+tabbarH, ScreenW , scrollViewH);
    
    // 创建频道View
    XBCommunityScrollView *scrollView = [XBCommunityScrollView ChannelWithLabels:self.channelTitles andFrame:frame];
    
    // 添加到view
    [self.view addSubview:scrollView];
    
    // 引用
    self.channelView = scrollView;
}

- (void)setupCollectionView
{
    // 添加collectionView
    // 获取频道View最大Y值
    CGFloat collectionY = CGRectGetMaxY(self.channelView.frame);
    
    // 计算frame
    CGRect rect = CGRectMake(0, collectionY, ScreenW, ScreenH - collectionY);
    
    // 创建flowLayout
    FlowLayout *flowLayout = [[FlowLayout alloc] init];
    
    // 创建collectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:rect collectionViewLayout:flowLayout];
    
    // 添加到view
    [self.view addSubview:collectionView];
    
    // 引用
    self.collectionView = collectionView;
    self.flowLayout = flowLayout;
    
    // 代理、数据源
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    // 其他设置
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.bounces = NO;
}

#pragma mark - ======== dealloc ========
- (void)dealloc
{
    // 当控制器销毁时取消监听
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ChannelTitleCurrenIndexChanged object:nil];
}

#pragma mark - ======== 数据懒加载 ========
- (NSArray *)channelTitles
{
    if (_channelTitles == nil) {
        
        // e.g 测试数据
        _channelTitles = @[@"精选",@"最新",@"知识",@"活动"];
    }
    return _channelTitles;
}

- (CGFloat)value
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _value = self.channelView.footLine.frame.origin.x;
    });
    
    return _value;
}
@end
